package myicesscheduler.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

public class FileDownloadController implements Controller
{
   protected final Log logger = LogFactory.getLog( getClass() );
   public static final String param_downloadFile = "file";
   public static final String param_folder = "folder";

   public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response )
         throws Exception
   {
      final String paramFile = request.getParameter( param_downloadFile );
      final String paramFolder = request.getParameter( param_folder );

      MyFolderInterface folder = MyFolderUtil.uploadFolder;
      if( "backup".equals( paramFolder ) ) folder = MyFolderUtil.backupFolder;

      if( folder.isRequireAdminPermission() && false == LoginController.isAdmin( request ) )
         return LectureListController.redirect();

      if( false == folder.isThereFile( paramFile ) )
         return handleRequest_FileNotFound( paramFile );

      return handleRequest_FileFound( folder, paramFile, request, response );
   }

   private ModelAndView handleRequest_FileFound( MyFolderInterface folder, String filenameWithPath,
         HttpServletRequest request, HttpServletResponse response )
   {
      final String filenameOnly = MyFileUtil.getFilenameOnly( filenameWithPath );
      final String mimeType = request.getSession().getServletContext().getMimeType( filenameOnly );
      final byte[] content = folder.readFile( filenameWithPath );

      response.setHeader( "Content-Disposition", "attachment; filename=\"" + filenameOnly + "\"" );
      response.setContentType( mimeType );
      response.setContentLength( content.length );
      try
      {
         FileCopyUtils.copy( content, response.getOutputStream() );
      } catch( IOException e )
      {
         logger.error( "IOException occurs on downloading a file: " + filenameWithPath );
         e.printStackTrace();
         return handleRequest_FileNotFound( filenameWithPath );
      }

      logger.info( "Downloading a file: " + filenameWithPath + " in " + mimeType );
      return null;
   }

   private ModelAndView handleRequest_FileNotFound( String downloadFile )
   {
      final ModelAndView mv = new ModelAndView( "fileDownload_FileNotFound" );
      mv.addObject( "downloadFile", downloadFile );
      return mv;
   }
}
